<?php

namespace App\AdminModule\Presenters;

use \Grido, 
    \Grido\Grid;
/**
 * Video view presenter.
 */
class VideoViewPresenter extends BasePresenter {
 
  /** @var \Kdyby\Doctrine\EntityManager @inject */
  public $em;
  
  private $video;
  
  /**
   * Delete view
   * @param type $id
   */
  public function handleDelete($id){
    $view = $this->em->getDao(VideoView::getClassName())->findOneBy(array('id'=> $id));
    
    if($view){
      // remove view
      $this->em->remove($view);
      $this->em->flush();
    }
    
    $this->flashMessage('Shlédnutí bylo smazáno', 'success');
    $this->redirect('VideoView:default');
  }
  
  /**
   * View grid
   * @param String $name
   * @return \Grido\Grid
   */
  public function createComponentVideoViewGrid($name){
      
    $g = new Grid($this, $name);
    
    $qb = $this->em->createQueryBuilder()
      ->addSelect('v.id AS id')
      ->addSelect('v.ip AS ip')
      ->addSelect('v.watched AS watched')
      ->addSelect('vi.webalize AS webalize')
      ->addSelect('u.login AS login')
      ->from(VideoView::getClassName(), ' v')
      ->leftJoin('v.user', 'u')
      ->innerJoin('v.video', 'vi');
    
    $views =  $qb->getQuery()->getArrayResult();

    // Grido data
    $g->model = $views;    
    
    $g->addColumnText('id', 'ID')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('ip', 'IP adresa')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('webalize', 'Link videa')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('login', 'Uživatel')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('watched', 'Shlédnuto')
        ->setSortable()
        ->setFilterText();
    
    $g->getColumn('watched')->setCustomRender(function($item){
      return $item['watched']->format('d.m.Y H:i:s');
    });
    
    // Create edit button
    $g->addActionHref('delete', 'Smazat', 'delete!')
      ->setIcon('remove')->setPrimaryKey('id');
    
    // Return grido
    $g->filterRenderType = Grido\Components\Filters\Filter::RENDER_INNER;
    $g->setExport();
    return $g;
  }
}
